﻿using System.Collections.Generic;
using ReadingList.Contracts.ServiceContracts;
using ReadingList.Contracts.DataContracts.QueryResults;
using ReadlingList.Services.Amazon;
using System.Configuration;

namespace ReadlingList.Services
{
    public class BookService : IBookService
    {

        /// <summary>
        /// Finds the book by title.
        /// </summary>
        /// <param name="keywords">The keywords.</param>
        /// <returns></returns>
        public List<BookQueryResult> FindBookByTitle(string keywords) {
            List<BookQueryResult> books = new List<BookQueryResult>();

            // Instantiate Amazon ProductAdvertisingAPI client
            AWSECommerceServicePortTypeClient amazonClient = new AWSECommerceServicePortTypeClient();

            // prepare an ItemSearch request
            ItemSearchRequest request = new ItemSearchRequest();
            request.SearchIndex = "Books";
            request.Title = keywords;
            request.ResponseGroup = new string[] { "Small" };

            ItemSearch itemSearch = new ItemSearch();
            itemSearch.Request = new ItemSearchRequest[] { request };
            itemSearch.AWSAccessKeyId = ConfigurationManager.AppSettings["accessKeyId"];

            // send the ItemSearch request
            ItemSearchResponse response = amazonClient.ItemSearch(itemSearch);
            
            foreach (var item in response.Items[0].Item) {
                books.Add(new BookQueryResult { Title = item.ItemAttributes.Title });
            }           

            return books;
        }
    }
}
